﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataAccessLayer
{
    public class UpdateStockDAL
    {
        StationeryInventoryEntities1 cntx;

        public UpdateStockDAL()
        {
            cntx = new StationeryInventoryEntities1();
        }

        public void updateOutstandingTable(string iCode, int updatedQuantity)
        {

            Stationery s = (from s1 in cntx.Stationeries
                            where s1.ItemCode == iCode
                            select s1).FirstOrDefault();   

            //s.AvailableQty = s.AvailableQty + Convert.ToInt32(updatedQuantity);
            int statAvailableQty = s.AvailableQty + Convert.ToInt32(updatedQuantity);

            List<OutstandingQty> oq = (from q in cntx.OutstandingQties
                                       where q.ItemCode == s.ItemCode
                                       select q).ToList();

            int availableQtyCounter = statAvailableQty;//(int)s.AvailableQty;

            foreach (OutstandingQty oa in oq)
            {
                DeptRequisition dp = new DeptRequisition();
                dp.DeptID = oa.DeptID;

                DeptRequisitionDetail dpr = new DeptRequisitionDetail();
                dpr.DeptRequisition = dp;
                dpr.ItemCode = oa.ItemCode;
                if (oa.OutstandingQty1 <= availableQtyCounter)
                {
                    dpr.NewRequestQty = oa.OutstandingQty1;
                    oa.Status = "New Request Raised";
                    availableQtyCounter = availableQtyCounter - (int)oa.OutstandingQty1;

                    cntx.DeptRequisitionDetails.Add(dpr);    
                    cntx.SaveChanges();
                }
                else
                {
                    if (availableQtyCounter != 0)
                    {
                        oa.OutstandingQty1 = oa.OutstandingQty1 - availableQtyCounter;
                        dpr.NewRequestQty = availableQtyCounter;
                        availableQtyCounter = availableQtyCounter - (int)dpr.NewRequestQty;

                        cntx.DeptRequisitionDetails.Add(dpr);
                        cntx.SaveChanges();     
                    }
                }    
            }

        }
    }
}
